package com.xidian.zhiancloud.service.accidentManage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.accidentmessage.AccidentMessageQO;
import com.xidian.zhiancloud.vo.accidentmessage.AccidentMessageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

@Service
public class AccidentMessageService extends ServiceImpl<AccidentMessageMapper, AccidentMessage> implements IService<AccidentMessage> {

    public int count = 0;
    public Date date = new Date();

    @Autowired
    private AccidentMessageMapper accidentMessageMapper;

    @Autowired
    private AccidentReviewMapper accidentReviewMapper;

    @Autowired
    private AccidentHandleMapper accidentHandleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    /**
     * 添加事故基本信息
     * @param accidentMessage
     */
    public Boolean addAccidentMessage(AccidentMessage accidentMessage){
        Date temp = new Date();

        if(count ==0){
            date = temp;
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(temp);
        cal2.setTime(date);

        if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
           cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
           cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)){
            count++;
        }else{
            count = 0;
        }

        String str = "SG" + cal1.get(Calendar.YEAR) + String.format("%02d",cal1.get(Calendar.MONTH)+1) +
                String.format("%02d",cal1.get(Calendar.DAY_OF_MONTH)) + String.format("%03d", count);

        accidentMessage.setAccidentNo(str);

        int result = accidentMessageMapper.insert(accidentMessage);
        if(result == 0){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }

        return true;
    }

    /**
     * 根据id获取事故基本信息
     * @param id
     * @return
     */
    public AccidentMessageVO getById(Long id){
        AccidentMessage accidentMessage = accidentMessageMapper.selectById(id);

        if(accidentMessage==null){
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }

        AccidentMessageVO vo = new AccidentMessageVO();
        BeanUtils.copyProperties(accidentMessage,vo);

        SysUser creator = sysUserMapper.selectById(vo.getCreator());
        Organization department = organizationMapper.selectById(vo.getDepartmentId());

        vo.setCreatorName(creator==null ? "该用户不存在":creator.getName());
        vo.setDepartmentName(department==null ? "该部门不存在":department.getName());

        return vo;
    }

    /**
     * 批量删除事故信息
     * @param idList
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean deleteByIds(Long[] idList){
        if(idList.length==0 || idList==null){
            return true;
        }

        for (Long id : idList) {
            int res1 = accidentMessageMapper.deleteById(id);

            if(res1==0){
                throw new CustomizeException(GeneralResponseEnums.DELETE_FAILED);
            }

            //根据事故id删除事故处理记录
            LambdaQueryWrapper<AccidentHandle> accidentHandleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            accidentHandleLambdaQueryWrapper.eq(AccidentHandle::getAccidentId,id);
            int res2 = accidentHandleMapper.delete(accidentHandleLambdaQueryWrapper);

            //根据事故id删除事故审核记录
            LambdaQueryWrapper<AccidentReview> accidentReviewLambdaQueryWrapper = new LambdaQueryWrapper<>();
            accidentReviewLambdaQueryWrapper.eq(AccidentReview::getAccidentId,id);
            int res3 = accidentReviewMapper.delete(accidentReviewLambdaQueryWrapper);


        }

        return true;
    }

    /**
     * 条件查询
     * @param accidentMessageQO 请求参数
     * @return 返回事故基本信息列表
     */
    public IPage<AccidentMessageVO> getListByQO(AccidentMessageQO accidentMessageQO){
        Page<AccidentMessageVO> page = new Page<>(accidentMessageQO.getCurrent(),accidentMessageQO.getSize());

        //排序
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);

        IPage<AccidentMessageVO> list = accidentMessageMapper.getListByQO(page, accidentMessageQO);

        list.getRecords().forEach(
                vo -> {
                    vo.setDepartmentName(vo.getDepartmentName()==null ? "该部门不存在" : vo.getDepartmentName());
                    vo.setCreatorName(vo.getCreatorName()==null ? "该用户不存在" : vo.getCreatorName());
                }
        );

        return list;
    }
}
